//
//  XRecentlyViewController.m
//  Bees
//
//  Created by Xiaohan on 2018/12/21.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "XRecentlyViewController.h"
#import "XHomeItemCell.h"
#import "LoginViewController.h"
#import "FoundServer.h"
#import "ScatterDappManager.h"
@interface XRecentlyViewController ()
@property (nonatomic,assign) XDAPP_RecentlyType thisType;
@property (nonatomic,strong) FoundServer *server;
@property (nonatomic,strong) NSArray<FoundRecommendModel*>*dataSource;
@end

@implementation XRecentlyViewController
- (instancetype)initWithType:(XDAPP_RecentlyType)type{
    self = [super initWithStyle:UITableViewStylePlain];
    self.thisType = type;
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getData];
}

- (void)getData{
    if (self.thisType == XDAPP_Recently) {
        self.dataSource = [kUserManager getRecentlyUsed];
        [self.tableView reloadData];
        if (kCurUser) {
            [self.server getCollectionListCompletion:^(BOOL success, NSString * _Nonnull msg) {
                [self endHeaderFooterRefreshing];
                if (success) {
                    NSMutableArray*ids = [NSMutableArray array];
                    [self.server.collectionList enumerateObjectsUsingBlock:^(FoundRecommendModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [ids addObject:obj.modelId];
                    }];
                    self.dataSource = [kUserManager getRecentlyUsed];
                    [self.dataSource enumerateObjectsUsingBlock:^(FoundRecommendModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            obj.isCollect = [ids containsObject:obj.modelId];
                    }];
                    [self.tableView reloadData];
                }else{
                    [self.view makeToast:msg];
                }
            }];
        }
    }else{
        [self.server getCollectionListCompletion:^(BOOL success, NSString * _Nonnull msg) {
            [self endHeaderFooterRefreshing];
            if (success) {
                self.dataSource = self.server.collectionList;
                [self.tableView reloadData];
            }else{
                [self.view makeToast:msg];
            }
        }];
    }
}

- (void)loadMore:(BOOL)isMore{
    if (!isMore) {
        [self getData];
    }
}

- (void)setupUI{
    self.tableView.mj_footer = nil;
    if (self.thisType == XDAPP_Recently) {
        self.title = XLocalized(@"最近使用");
        UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, AdaptedWidth(40))];
        UIButton*btn = [[UIButton alloc]initWithFrame:CGRectMake(kNormalSpace, 0, headView.width-2*kNormalSpace, headView.height)];
        ViewRadius(btn, AdaptedWidth(13));
        btn.backgroundColor = UIColorHex(#999999);
        [headView addSubview:btn];

        UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(btn.left+AdaptedWidth(10), 0, 200, headView.height)];
        titleLab.font = kDefaultFont(16);;
        titleLab.textColor = UIColor.whiteColor;
        [headView addSubview:titleLab];
        titleLab.text = XLocalized(@"我的收藏");
        UIImageView*imageV = [[UIImageView alloc]initWithFrame:CGRectMake(btn.right-AdaptedWidth(18), AdaptedWidth(12), AdaptedWidth(17), AdaptedWidth(17))];
        imageV.image = IMAGE_NAMED(@"white_arrow");
        [headView addSubview:imageV];
        self.tableView.tableHeaderView = headView;
        kWeakSelf(self);
        [btn addTapBlock:^(UIButton * _Nonnull btn) {
            if (!kCurUser) {
                [XAlertTool alertTitle:XLocalized(@"您尚未登录BEES账号，无法进行收藏操作,是否登录？") message:nil cancelAction:^{
                    
                } sureAction:^{
                    LoginViewController*login = [LoginViewController new];
                    [weakself.navigationController hh_pushBackViewController:login];
                }];
                return;
            }
            XRecentlyViewController *vc = [[XRecentlyViewController alloc]initWithType:XDAPP_Collection];
            [weakself.navigationController pushViewController:vc animated:YES];
        }];
    }else{
        self.title = XLocalized(@"我的收藏");
    }
    self.tableView.rowHeight = AdaptedWidth(83);
    self.tableView.tableFooterView = [UIView new];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    XHomeItemCell *cell = [XHomeItemCell cellForTableView:tableView];
    FoundRecommendModel*model = [self.dataSource objectOrNilAtIndex:indexPath.row];
    [cell.imageV sd_setImageWithURL:String_To_URL(model.logo) placeholderImage:nil];
    cell.titleLab.text = model.name;
    cell.subLab.text = model.introduction;
    if (self.thisType == XDAPP_Recently) {
        cell.collectionIcon.hidden = !model.isCollect;
    }
    return cell;
}

- (NSArray*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
//    UITableViewRowActionStyleNormal：灰底白字
//      UITableViewRowActionStyleDefault：红底白字
//      UITableViewRowActionStyleDestructive：红底白字
    FoundRecommendModel *model = [self.dataSource objectAtIndex:indexPath.row];
    if (self.thisType==XDAPP_Recently ) {
        if (!model.isCollect) {
            kWeakSelf(self);
            UITableViewRowAction * collectionAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:XLocalized(@"收藏") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                [tableView setEditing:NO animated:YES];
                DLog(@"%@",XLocalized(@"收藏"));
                if (!kCurUser) {
                    [XAlertTool alertTitle:XLocalized(@"您尚未登录BEES账号，无法进行收藏操作,是否登录？") message:nil cancelAction:^{
                        
                    } sureAction:^{
                        LoginViewController*login = [LoginViewController new];
                        [weakself.navigationController hh_pushBackViewController:login];
                    }];
                    return;
                }
                self.server.collectionId = model.modelId;
                [MBProgressHUD showLoadTitile:@"" ToView:self.view];
                [self.server postCollectionListCompletion:^(BOOL success, NSString * _Nonnull msg) {
                    [MBProgressHUD hideHUDForView:self.view];
                    [self.view makeToast:msg];
                    if (success) {
                        model.isCollect = YES;
                        [self.tableView reloadData];
                    }
                }];
            }];
            return @[collectionAction];
        }else{
            UITableViewRowAction * delCollectionAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:XLocalized(@"取消收藏") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
                [tableView setEditing:NO animated:YES];
                DLog(@"%@",XLocalized(@"取消收藏"));
                self.server.collectionId = model.modelId;
                [MBProgressHUD showLoadTitile:@"" ToView:self.view];
                [self.server putCollectionListCompletion:^(BOOL success, NSString * _Nonnull msg) {
                    [MBProgressHUD hideHUDForView:self.view];
                    [self.view makeToast:msg];
                    if (success) {
                        model.isCollect = NO;
                        [self.tableView reloadData];
                    }
                }];
            }];
            return @[delCollectionAction];
        }
    }else{
        UITableViewRowAction * delCollectionAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:XLocalized(@"删除") handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
            [tableView setEditing:NO animated:YES];
            self.server.collectionId = model.modelId;
            [MBProgressHUD showLoadTitile:@"" ToView:self.view];
            [self.server putCollectionListCompletion:^(BOOL success, NSString * _Nonnull msg) {
                [MBProgressHUD hideHUDForView:self.view];
                [self.view makeToast:msg];
                if (success) {
                    NSMutableArray*data = self.dataSource.mutableCopy;
                    [data removeObjectAtIndex:indexPath.row];
                    self.dataSource = data.copy;
                    [self.tableView reloadData];
                }
            }];
        }];
        return @[delCollectionAction];
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [ScatterDappManager manager:self forDapp:[self.dataSource objectAtIndex:indexPath.row]];
}

#pragma mark - getter
- (FoundServer*)server{
    if (!_server) {
        _server = [FoundServer new];
    }
    return _server;
}

@end
